package org.JWCB.friend.service.user;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.JWCB.common.core.constants.UserConstants;
import org.JWCB.common.core.domain.dto.QueryDto;
import org.JWCB.common.core.domain.vo.TableDataInfo;
import org.JWCB.common.core.utils.ThreadLocalUtil;
import org.JWCB.friend.domain.message.entity.Message;
import org.JWCB.friend.domain.message.entity.MessageText;
import org.JWCB.friend.domain.message.vo.MessageListItemVo;
import org.JWCB.friend.manager.MessageCacheManager;
import org.JWCB.friend.mapper.user.UserMessageMapper;
import org.JWCB.friend.mapper.user.UserMessageTextMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserMessageService {


    @Autowired
    private UserMessageTextMapper userMessageTextMapper;


    @Autowired
    private UserMessageMapper userMessageMapper;

    @Autowired
    private MessageCacheManager messageCacheManager;
    /**
     * 消息列表
     */
    public TableDataInfo list(QueryDto queryDto) {
        Long userId = ThreadLocalUtil.get(UserConstants.USER_ID,Long.class);
        Long listSize = messageCacheManager.getListSize(userId);
        List<MessageListItemVo> messageListItemVoList = null;
        if(listSize == null || listSize == 0) {
            // 从数据库获取并刷新redis缓存
            PageHelper.startPage(queryDto.getPageNum(),queryDto.getPageSize());
            messageListItemVoList = userMessageTextMapper.selectMessageList(userId);
            messageCacheManager.refreshCache(userId);
            listSize = new PageInfo<>(messageListItemVoList).getTotal();
        }else {
            // 从缓存中获取
            messageListItemVoList = messageCacheManager.getMessageList(queryDto,userId);
            listSize = messageCacheManager.getListSize(userId);
        }
        if(CollectionUtil.isEmpty(messageListItemVoList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(messageListItemVoList,listSize);
    }


    /**
     * 删除消息
     */
    @Transactional
    public int del(Long textId) {
        Long userId = ThreadLocalUtil.get(UserConstants.USER_ID,Long.class);
        int res = userMessageMapper.delete(new LambdaQueryWrapper<Message>()
                .eq(Message::getTextId, textId)
                .eq(Message::getAcceptorId, userId));
        if(res <= 0) {
            return res;
        }
        res = userMessageTextMapper.delete(new LambdaQueryWrapper<MessageText>()
                .eq(MessageText::getTextId,textId));
        if(res <= 0) {
            return res;
        }
        messageCacheManager.delCache(userId,textId);
        return res;
    }
}
